import React, { Component } from 'react'
import { LockOutlined, UserOutlined } from '@ant-design/icons';
import {  Checkbox, Form, Input } from 'antd';
import style from '../Login.module.less'
import {toast} from "react-toastify";
import {PhoneNumberRequest, registerRequest, usernamesRequest} from "@requests/auth";
import {Link, withRouter} from 'react-router-dom'
import {connect} from "react-redux";
import {saveUserCreator} from "@creators/userCreator";
 class Logon extends Component {
    state={
        users:{
            username : '',
            password:'',
            password2:'',
            phone_number : '',
            allow:false
        },
        userError:{
            nameError : '名字不能为空！',
            passwordError: '密码不能为空！',
            phoneError: '手机不能为空！'
        },
        //记录名字是否注册状态
        usernamesRequestStatus:'idle',
        //记录名字是否注册错误信息
        usernamesRequestError:null,
        // 记录注册请求状态
        registerRequestStatus: "idle",
        // 记录注册请求错误信息
        registerRequestError: null,
        // 记录手机号请求状态
        mobileRequestStatus : 'idle',
        // 记录手机号请求错误信息
        mobileRequestError:null
    }
    //提交注册表单
    onFinish = async (values) => {
        // console.log(this.state.users)
        console.log(1)
        if(this.state.users.allow !== true) {
            toast.warn('请勾选用户协议', {
                autoClose: 1000,
            })
            return
        }
       if(this.state.registerRequestStatus === 'loading'){
           toast.warn('请勿多次点击', {
               autoClose: 1000,
           });
           return
       }
       this.setState({
           registerRequestStatus:"loading",
           registerRequestError:null
       })
        try {
            const response = await registerRequest(this.state.users);
            this.setState({
                registerRequestStatus:"success",
                registerRequestError:null
            })
            if(response.code !== 200) return
            toast.success("注册成功", {
                // 自定关闭事件
                autoClose: 1000
            });
            // console.log(response)
            this.props.dispatch(saveUserCreator(response.user));
            sessionStorage.setItem("user",JSON.stringify(response.user));
            this.props.history.replace('/')
        } catch (error){
           this.setState({
               registerRequestStatus:'Error',
               registerRequestError:error
           })
        }
    };
    // 更新表单状态
    updateFormState =(event) => {
        // toast.success("登录成功", { position: "top-center", autoClose: 1000 });
        this.setState({
            users : {
                ...this.state.users,
                [event.target.name] : event.target.name === 'allow' ? event.target.checked : event.target.value
            }
        })
    }
    //判断用户名是否注册
    usernamesRequest = async (event) => {
        if(this.state.users.username.length < 4 || this.state.users.username.length > 15) {
            toast.warn('用户名格式必须4-15位', {
                position: "top-center",
                autoClose: 1000,
            })
            return
        }
        if(this.state.usernamesRequestStatus === 'loading') return
        this.setState({
            usernamesRequest : 'loading',
            usernamesRequestError : null
        })
        try{
            const response = await usernamesRequest(this.state.users.username)
            if(response.code === 400){
                toast.warn('该名字已被注册！', {
                    position: "top-center",
                    autoClose: 1000,
                })
            }
            this.setState({
                usernamesRequest:'success',
                usernamesRequestError:null
            })
        } catch (error){
            this.setState({
                usernamesRequest : 'error',
                usernamesRequestError:error
            })
        }
    }
    Blur = async () => {
        if(this.state.users.password.length < 8 || this.state.users.password.length > 15){
            toast.warn('密码格式为8-15位', {
                position: "top-center",
                autoClose: 1000,
            });
        }
        if(this.state.users.password !== this.state.users.password2){
            toast.warn('两次密码不一致', {
                position: "top-center",
                autoClose: 1000,
            });
        }

    }
    //判断手机号是否重复注册
    mobileBlur = async () => {
        if(this.state.users.phone_number.length !== 11){
            return toast.warn('手机号格式不正确', {
                position: "top-center",
                autoClose: 1000,
            });
        }
        if(this.state.mobileRequestStatus === 'loading') return
        this.setState({
            mobileRequestStatus:'loading',
            mobileRequestError:null
        })
        try{
            const response = await PhoneNumberRequest(this.state.users.phone_number)
            if (response.code === 400) {
                return toast.warn('该手机号已经被注册', {
                    position: "top-center",
                    autoClose: 1000,
                })
                this.setState({
                    mobileRequestStatus:'success',
                    mobileRequestError : null
                })
            }
        }catch (error){
            this.setState({
                mobileRequestStatus : 'Error',
                mobileRequestError:error
            })
        }
    }
    render() {
        const { onChangPage } = this.props
        return (
            <div className={style.littleBox} style={{ paddingTop: '5vh' }}>

                <Form
                    name="normal_login"
                    className="login-form"
                    initialValues={{ remember: true }}
                    onFinish={this.onFinish}
                >
                    <Form.Item
                        name="username"
                        rules={[{ required: true, message: this.state.userError.nameError}]}
                        className={style.aaaa}
                    >
                        <Input name="username" prefix={<UserOutlined className="site-form-item-icon" />}
                               value = {
                                   this.state.users.username
                               }
                               onChange={this.updateFormState}
                               placeholder="请输入用户名"
                               onBlur={this.usernamesRequest}
                        />
                    </Form.Item>
                    <Form.Item
                        className={style.aaaa}
                        name="password"
                        rules={[{ required: true, message: this.state.userError.passwordError }]}
                    >
                        <Input
                            prefix={<LockOutlined className="site-form-item-icon" />}
                            type="password"
                            name="password"
                            placeholder="输入密码"
                            value = {
                                this.state.users.password
                            }
                            onChange={this.updateFormState}
                        />
                    </Form.Item>
                    <Form.Item
                        className={style.aaaa}
                        name="password2"
                        rules={[{ required: true, message: this.state.userError.passwordError }]}
                    >
                        <Input
                            prefix={<LockOutlined className="site-form-item-icon" />}
                            type="password"
                            name="password2"
                            placeholder="再次输入密码"
                            value = {
                                this.state.users.password2
                            }
                            onChange = {this.updateFormState}
                            onBlur = {this.Blur}
                        />
                    </Form.Item>
                    <Form.Item
                        name="phone_number"
                        // label="Phone Number"
                        className={style.aaaa}
                        rules={[{ required: true, message: this.state.userError.phoneError }]}
                    >
                        <Input
                            // addonBefore={prefixSelector}
                            name="phone_number"
                            placeholder='请输入手机号' style={{ width: '100%' }}
                            value={this.state.users.phone_number}
                            onChange = {this.updateFormState}
                            onBlur = {this.mobileBlur}
                        />
                    </Form.Item>
                    <Form.Item style={{ margin: '0' }}>
                        <Form.Item name="name" valuePropName="checked" noStyle >
                            <Checkbox name='allow' checked={this.state.users.allow} onChange={this.updateFormState}>用户隐私协议</Checkbox>
                        </Form.Item>
                        <Link className="login-form-forgot" to='/Forget'>忘记密码</Link>
                    </Form.Item>

                    <Form.Item>
                        <button style={{ width: "20vw", display: 'block', margin: "0 auto", marginBottom: '5px' ,border:0,backgroundColor:'rgb(64,150,255)',color : 'white' ,height : '2vw',borderRadius:'5px' }}  type="submit" className="login-form-button">
                            立即注册
                        </button>
                        <a name='logon' onClick={onChangPage} >已有账号？立刻登录</a>
                    </Form.Item>
                </Form>
            </div>
        )
    }
}

export default connect()(withRouter(Logon))
